package com.oa.tools.utils.http;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.oa.tools.utils.ObjectUtil;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttpClientUtil {
	public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
	public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded");
	public static String htmlUrl = "";
	public static Map<String, Object> dep_email_id = new HashMap<String, Object>();
	public static Map<String, String> familynameMap = new HashMap<String, String>();

	public static String[] httpGet(String url, Map<String, String> params, Set<String> cookies) throws IOException {
		StringBuilder url_sb = new StringBuilder();
		url_sb.append(url);

		if ((params != null) && (params.size() > 0)) {
			url_sb.append('?');
			Set<String> paramsKeys = params.keySet();
			for (Iterator<String> localIterator = paramsKeys.iterator(); localIterator.hasNext(); url_sb.append('&')) {
				String key = (String) localIterator.next();
				url_sb.append(key);
				url_sb.append('=');
				url_sb.append((String) params.get(key));
			}
		}

		OkHttpClient httpClient = new OkHttpClient();
		Request request = null;
		if (cookies == null)
			request = new Request.Builder().url(url_sb.toString()).build();
		else {
			request = new Request.Builder().url(url_sb.toString()).header("Cookie", mergeCookieStr(cookies)).build();
		}

		Response response = httpClient.newCall(request).execute();
		String res_cookies = response.headers().values("Set-Cookie").toString();
		return new String[] { response.body().string(), res_cookies.substring(1, res_cookies.length() - 1) };
	}

	public static String[] httpPost(String url, Map<String, String> params, Set<String> cookies) throws IOException {
		OkHttpClient httpClient = new OkHttpClient();
		FormBody.Builder builder = new FormBody.Builder();

		if ((params != null) && (params.size() > 0)) {
			Set<String> paramsKeys = params.keySet();
			for (String key : paramsKeys) {
				builder.add(key, (String) params.get(key));
			}
		}

		RequestBody formBody = builder.build();
		Request request = null;
		if (cookies == null)
			request = new Request.Builder().url(url).post(formBody).build();
		else {
			request = new Request.Builder().url(url).header("Cookie", mergeCookieStr(cookies)).post(formBody).build();
		}

		Response response = httpClient.newCall(request).execute();
		String res_cookies = response.headers().values("Set-Cookie").toString();
		String cookiesStr = res_cookies.substring(1, res_cookies.length() - 1);
		String[] url_arr = response.request().url().toString().split(";");
		if (url_arr.length == 2) {
			if (cookiesStr.length() == 0)
				cookiesStr = new StringBuilder().append(cookiesStr).append(url_arr[1]).toString();
			else if (cookiesStr.endsWith(";"))
				cookiesStr = new StringBuilder().append(cookiesStr).append(url_arr[1]).toString();
			else {
				cookiesStr = new StringBuilder().append(cookiesStr).append(";").append(url_arr[1]).toString();
			}

		}

		return new String[] { response.body().string(), cookiesStr };
	}

	public static String[] httpUploadExcel(String url, Map<String, String> params, Set<String> cookies, File file)
			throws IOException {
		StringBuilder url_sb = new StringBuilder();
		url_sb.append(url);

		if ((params != null) && (params.size() > 0)) {
			url_sb.append('?');
			Set<String> paramsKeys = params.keySet();
			for (Iterator<String> localIterator = paramsKeys.iterator(); localIterator.hasNext(); url_sb.append('&')) {
				String key = (String) localIterator.next();
				url_sb.append(key);
				url_sb.append('=');
				url_sb.append((String) params.get(key));
			}
		}

		OkHttpClient httpClient = new OkHttpClient();
		MediaType type = MediaType.parse(new StringBuilder().append("form-data; name=\"file\"; filename=\"")
				.append(file.getName()).append("\"").toString());
		MediaType type1 = MediaType.parse("text/xml;charset=utf-8");
		RequestBody fileBody = RequestBody.create(type, file);
		//FormBody paramsBody = new FormBody.Builder().add("fdId", "160110a35c84fc4519742994cb99094d").build();
		RequestBody textBody = RequestBody.create(type1, "160110a35c84fc4519742994cb99094d");

		RequestBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addPart(fileBody)
				.addPart(Headers.of(new String[] { "Content-Disposition", "form-data; name=\"fdId\"" }),
						textBody)
				.addPart(Headers.of(new String[] { "Content-Disposition",
						new StringBuilder().append("form-data; name=\"file\"; filename=\"").append(file.getName())
								.append("\"").toString() }),
						fileBody)
				.build();

		Request.Builder requestBuilder = new Request.Builder().url(url_sb.toString())
				.header("Content-Type", "application/vnd.ms-excel").post(multipartBody);

		Request request = null;
		if (cookies == null)
			request = requestBuilder.build();
		else {
			request = requestBuilder.header("Cookie", mergeCookieStr(cookies)).build();
		}

		Response response = httpClient.newCall(request).execute();
		String res_cookies = response.headers().values("Set-Cookie").toString();

		return new String[] { response.body().string(), res_cookies.substring(1, res_cookies.length() - 1) };
	}
	
	public static String[] httpUpload(String url, Map<String, String> params,Map<String, String> headerParam,  Set<String> cookies, File file)
			throws IOException {
		StringBuilder url_sb = new StringBuilder();
		url_sb.append(url);

		if ((params != null) && (params.size() > 0)) {
			url_sb.append('?');
			Set<String> paramsKeys = params.keySet();
			for (Iterator<String> localIterator = paramsKeys.iterator(); localIterator.hasNext(); url_sb.append('&')) {
				String key = (String) localIterator.next();
				url_sb.append(key);
				url_sb.append('=');
				url_sb.append((String) params.get(key));
			}
		}

		OkHttpClient httpClient = new OkHttpClient();
		MediaType type = MediaType.parse(new StringBuilder().append("form-data; name=\"file\"; filename=\"")
				.append(file.getName()).append("\"").toString());
		MediaType type1 = MediaType.parse("text/xml;charset=utf-8");
		RequestBody fileBody = RequestBody.create(type, file);
		//FormBody paramsBody = new FormBody.Builder().add("fdId", "160110a35c84fc4519742994cb99094d").build();
		RequestBody textBody = RequestBody.create(type1, "160110a35c84fc4519742994cb99094d");

		RequestBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addPart(fileBody)
				.addPart(Headers.of(new String[] { "Content-Disposition", "form-data; name=\"fdId\"" }),
						textBody)
				.addPart(Headers.of(new String[] { "Content-Disposition",
						new StringBuilder().append("form-data; name=\"file\"; filename=\"").append(file.getName())
								.append("\"").toString() }),
						fileBody)
				.build();

		Request.Builder requestBuilder = new Request.Builder().url(url_sb.toString())
				.header("Content-Type", "application/vnd.ms-excel").post(multipartBody);
		
		if((headerParam != null) && (headerParam.size() > 0)) {
			Set<String> paramsKeys = headerParam.keySet();
			for(Iterator<String> localIterator = paramsKeys.iterator(); localIterator.hasNext(); ){
				String key = (String) localIterator.next();
				requestBuilder.header(key, (String) headerParam.get(key));
			}
		}
		
		Request request = null;
		if (cookies == null)
			request = requestBuilder.build();
		else {
			request = requestBuilder.header("Cookie", mergeCookieStr(cookies)).build();
		}

		Response response = httpClient.newCall(request).execute();
		String res_cookies = response.headers().values("Set-Cookie").toString();

		return new String[] { response.body().string(), res_cookies.substring(1, res_cookies.length() - 1) };
	}

	public static Set<String> parse2Cookies(String cookiesStr) {
		String[] cookieArr = cookiesStr.split(";");
		Set<String> cookies = new HashSet<String>();
		for (String cookieStr : cookieArr) {
			cookies.add(cookieStr);
		}
		return cookies;
	}

	public static String mergeCookieStr(Set<String> cookies) {
		StringBuilder cookies_sb = new StringBuilder();
		if ((cookies != null) && (cookies.size() > 0)) {
			for (Iterator<String> localIterator = cookies.iterator(); localIterator.hasNext(); cookies_sb.append(';')) {
				String key = (String) localIterator.next();
				key = key.replace("jsessionid", "JSESSIONID");
				cookies_sb.append(key);
			}
		}
		return cookies_sb.toString();
	}

	public static String[] httpJsonPost(String url, Map<String,Object> params, Set<String> cookies)
			throws IOException {
		OkHttpClient okHttpClient = new OkHttpClient();

		String json = ObjectUtil.object2Json(params);

		RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);

		Request request = new Request.Builder().url(url).post(requestBody).build();

		Response response = okHttpClient.newCall(request).execute();
		String res_cookies = response.headers().values("Set-Cookie").toString();
		return new String[] { response.body().string(), res_cookies.substring(1, res_cookies.length() - 1) };
	}

	public static String escapeExprSpecialWord(String keyword) {
		if ((keyword != null) && (keyword.length() > 0)) {
			String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
			for (String key : fbsArr) {
				if (keyword.contains(key)) {
					keyword = keyword.replace(key, new StringBuilder().append("\\").append(key).toString());
				}
			}
		}
		return keyword;
	}
	
	public static String updateEmail(Map<String, Object> params) throws IOException {
		String url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=wmd96f35beef7a0a0f&corpsecret=oycrJ9_5zYag_urUZZzmq_t5tas-foPgj2xtfcg1SN4fqEoyyDk6fPYncu5NAg_E";
		String[] bodyString = OKHttpClientUtil.httpGet(url, null, null);

		String access_token = ObjectUtil.json2Map(bodyString[0]).get("access_token").toString();

		url = "https://api.exmail.qq.com/cgi-bin/user/update?access_token=" + access_token;

		bodyString = OKHttpClientUtil.httpJsonPost(url, params, null);
		return bodyString[0];
	}
	
	
}